package com.iamteer.day18.longtext;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

public class AppText {
	private Connection con;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	private String url = "jdbc:mysql:///day18";
	private String user = "root";
	private String password = "123456";
	
	//1 保存大文本（写）
	@Test
	public void testSaveText() {
		String sql = "INSERT INTO test(content) VALUES(?)";
		FileReader reader = null;
		try {
			//连接数据库
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			
			//获取 PreparedStatement 对象
			pstmt = con.prepareStatement(sql);
			
			//设置参数
			String path = AppText.class.getResource("test.txt").getPath();
			reader = new FileReader(new File(path));
			pstmt.setCharacterStream(1, reader);
			
			//执行
			pstmt.executeUpdate();
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				reader.close();
				pstmt.close();
				con.close();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	//2 读取大文本
	@Test
	public void testGetAsText() {
		String sql = "SELECT * FROM test";
		//连接数据库
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			
			//获取 PreparedStatement 对象
			pstmt = con.prepareStatement(sql);
			
			rs = pstmt.executeQuery();
			
			if (rs.next()) {
				//获取方式 1
//				Reader reader = rs.getCharacterStream("content");
				
				//获取方式 2
				System.out.println(rs.getString("content"));
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				rs.close();
				pstmt.close();
				con.close();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}			
		}
	}
}
